<!--
  * 预订货
  *
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-card size="small" :bordered="false" :hoverable="false" class="query-form-wrapper smart-margin-bottom10 smart-radius-2">
    <a-form>
      <a-row :gutter="[8, 10]">
        <a-col :span="5.5">
          <a-form-item label="单据日期" class="smart-margin-bottom0">
            <custom-range-picker v-model:value="queryForm.create_time" />
          </a-form-item>
        </a-col>
        <a-col :span="3.5">
          <a-form-item label="单据编号" class="smart-margin-bottom0">
            <a-input v-model:value.trim="queryForm.no" placeholder="单据编号" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="3">
          <a-form-item label="订货名称" class="smart-margin-bottom0">
            <a-input v-model:value.trim="queryForm.name" placeholder="订货名称" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="3">
          <a-form-item label="门店名称" class="smart-margin-bottom0">
            <Select name="Store" v-model:value="queryForm.store_id" placeholder="门店名称" />
          </a-form-item>
        </a-col>
        <a-col :span="3">
          <a-form-item label="业务员" class="smart-margin-bottom0">
            <Select name="Salesman" v-model:value="queryForm.salesman_id" placeholder="业务员" />
          </a-form-item>
        </a-col>

        <a-col :span="5">
          <a-button-group>
            <a-button type="primary" html-type="submit" @click="onSearch" v-privilege="'goods:query'">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-button>
            <a-button @click="resetQuery" v-privilege="'goods:query'">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
            <SearchFormCollapse v-model="expand" />
          </a-button-group>
        </a-col>
        <template v-if="expand">
          <a-col :span="3">
            <a-form-item label="单据状态" class="smart-margin-bottom0">
              <EnumSelect enum-name="STATUS_THREE_ENUM" v-model:value="queryForm.status" placeholder="单据状态" />
            </a-form-item>
          </a-col>
          <a-col :span="3">
            <a-form-item label="履约状态" class="smart-margin-bottom0">
              <EnumSelect enum-name="PERFORMANCE_TYPE_ENUM" v-model:value="queryForm.performance_status" placeholder="履约状态" />
            </a-form-item>
          </a-col>
        </template>
      </a-row>
    </a-form>
  </a-card>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true" class="query-table-wrapper">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button @click="addOrder" type="primary" v-privilege="'goods:add'">
          <template #icon>
            <PlusOutlined />
          </template>
          新建
        </a-button>

        <a-button @click="onExport" type="primary" v-privilege="'goods:exportGoods'">
          <template #icon>
            <ExportOutlined />
          </template>
          导出
        </a-button>
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.ERP.GOODS" :refresh="queryData" />
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->
    <div class="table-wrapper">
      <a-table size="small" :dataSource="tableData" :columns="columns" :loading="tableLoading" rowKey="id" bordered :scroll="{ x: 'max-content', y: tableScrollY }" :pagination="false" :showSorterTooltip="false" :row-selection="{ fixed: true }">
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.dataIndex === 'no'">
            <CopyText :text="text">
              <a @click="detail(record)">{{ text }}</a>
            </CopyText>
          </template>
          <template v-if="column.dataIndex === 'payment'">
            <span>先收款再发货</span>
          </template>
          <template v-if="column.dataIndex === 'status'">
            <a-tag :color="tagType[text]">{{ getDescByValue('STATUS_THREE_ENUM', text) }}</a-tag>
          </template>
          <template v-if="column.dataIndex === 'performance_status'">
            <a-tag :color="tagType[text]">{{ getDescByValue('PERFORMANCE_TYPE_ENUM', text) }}</a-tag>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <div class="smart-table-operate">
              <a-button @click="detail(record)" type="link" style="color: #97999c" v-privilege="'goods:update'">详情</a-button>
              <template v-if="record.status === 1">
                <a-button @click="addOrder(record)" type="link" v-privilege="'goods:update'">编辑</a-button>
                <a-button @click="deleteData(record.id, record.no)" type="link" danger v-privilege="'goods:update'">删除</a-button>
                <a-button @click="review(record)" type="link" v-privilege="'goods:update'">审核</a-button>
              </template>
              <template v-if="record.status === 2 && record.performance_status !== 3">
                <a-button @click="terminate(record)" type="link" v-privilege="'goods:update'">终止</a-button>
              </template>
            </div>
          </template>
        </template>
        <template #summary>
          <a-table-summary>
            <a-table-summary-row>
              <a-table-summary-cell :index="0">总计</a-table-summary-cell>
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell>
                <a-typography-text type="danger">{{ Number(total_amount.total_price).toFixed(2) }}</a-typography-text>
              </a-table-summary-cell>
              <a-table-summary-cell>
                <a-typography-text type="danger">{{ Number(total_amount.total_fulfilled_price).toFixed(2) }}</a-typography-text>
              </a-table-summary-cell>
              <a-table-summary-cell>
                <a-typography-text type="danger">{{ Number(total_amount.total_un_fulfilled_price).toFixed(2) }}</a-typography-text>
              </a-table-summary-cell>
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell :index="columns.length" />
            </a-table-summary-row>
          </a-table-summary>
        </template>
      </a-table>
    </div>

    <div class="smart-query-table-page query-table-page">
      <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS" :defaultPageSize="queryForm.limit" v-model:current="queryForm.page" v-model:pageSize="queryForm.limit" :total="total" @change="queryData" @showSizeChange="queryData" :show-total="(total) => `共${total}条`" />
    </div>

    <ReservationDetailsModal ref="detailRef" />
    <ReservationPrintModal ref="printRef" />
    <ReservationFormModal ref="formModal" @reloadList="queryData" />
  </a-card>
</template>
<script setup lang="ts">
import CustomRangePicker from '@/components/business/custom-range-picker/index.vue'
import ReservationFormModal from './components/reservation-form-modal.vue'
import ReservationDetailsModal from './components/reservation-details-modal.vue'
import ReservationPrintModal from './components/reservation-print-modal.vue'
import { contractApi } from '@/api/business/marketing/contract-api'
import { PAGE_SIZE_OPTIONS, DEFAULT_TIME_RANGE } from '@/constants/system/common-const'
import SearchFormCollapse from '@/components/support/search-form-collapse/index.vue'
import Select from '@/components/business/select/index.vue'
import EnumSelect from '@/components/framework/enum-select/index.vue'
import TableOperator from '@/components/support/table-operator/index.vue'
import { TABLE_ID_CONST } from '@/constants/support/table-id-const'
import _ from 'lodash'
import { message, Modal } from 'ant-design-vue'
import { errorSentry } from '@/lib/error-sentry'
import { useQuery } from '@/hooks/web/use-query-hook'
import { QUERY_FORM_OP } from '@/constants/support/query-form-op-const'
import { useEnums } from '@/hooks/plugins/useEnums'
import { useAppConfigStore } from '@/store/modules/app-store'
import { useResize } from '@/hooks/web/use-resize-hook'
import { useLoadingStore } from '@/store/modules/loading-store'
import { ref, onMounted } from 'vue'

const appConfigStore = useAppConfigStore()
const loadingStore = useLoadingStore()
const { getDescByValue } = useEnums()
const tagType = ref({
  1: 'error',
  2: 'warning',
  3: 'processing',
  4: 'success',
  5: 'green',
  6: 'orange',
  7: 'cyan',
  8: 'purple'
})
// ----------------------------- 计算表格高度 -----------------------------
const { tableScrollY, expand } = useResize()

// ---------------------------- 表格列 ----------------------------

const columns = computed(() => [
  {
    title: '单据编号',
    dataIndex: 'no',
    width: appConfigStore.$state.compactFlag ? 240 : 270
  },
  {
    title: '订货名称',
    dataIndex: 'name'
  },
  {
    title: '收款方式',
    dataIndex: 'payment'
  },
  {
    title: '门店名称',
    dataIndex: ['store', 'store_name']
  },
  {
    title: '业务员',
    dataIndex: ['salesman', 'rename']
  },
  {
    title: '订货金额(元)',
    dataIndex: 'detail_sum'
  },
  {
    title: '已履约金额(元)',
    dataIndex: 'fulfilled_price'
  },
  {
    title: '未履约金额(元)',
    dataIndex: 'un_fulfilled_price',
    width: 120
  },
  {
    title: '单据状态',
    dataIndex: 'status',
    width: 120
  },
  {
    title: '履约状态',
    dataIndex: 'performance_status',
    width: 100
  },
  {
    title: '制单时间',
    dataIndex: 'create_time'
  },
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    width: appConfigStore.$state.compactFlag ? 180 : 200
  }
])

// ---------------------------- 查询数据表单和方法 ----------------------------
const total_amount = ref({
  total_fulfilled_price: 0,
  total_price: 0,
  total_un_fulfilled_price: 0
})
const { queryForm, queryFormOp, tableData, tableLoading, total, resetQuery, onSearch, queryData, deleteData } = useQuery({
  fetchDataApi: async (params) => {
    const res = await contractApi.queryBookList(params)
    total_amount.value = res.data.sumData
    return {
      list: res.data.list.data,
      total: res.data.list.total
    }
  },
  fetchDeleteApi: async (id) => {
    const res = await contractApi.delBook({ id })
    return !!res
  },
  queryFormFilter: {
    create_time: DEFAULT_TIME_RANGE.value,
    no: '',
    name: '',
    store_id: null,
    salesman_id: null,
    status: null,
    performance_status: null
  },
  queryFormOp: {
    create_time: QUERY_FORM_OP['范围查询'],
    no: QUERY_FORM_OP['模糊查询'],
    name: QUERY_FORM_OP['模糊查询'],
    store_id: QUERY_FORM_OP['全等查询'],
    salesman_id: QUERY_FORM_OP['全等查询'],
    status: QUERY_FORM_OP['全等查询'],
    performance_status: QUERY_FORM_OP['全等查询']
  }
})

onMounted(() => {
  queryData()
})

// ---------------------------- 添加/修改 ----------------------------
const formModal = ref()

function addOrder(rowData) {
  formModal.value.showDrawer(rowData)
}

// ---------------------------- 详情 ----------------------------
const detailRef = ref()

const detail = async (rowData) => {
  try {
    const res = await contractApi.detailBook({ id: rowData.id })
    detailRef.value.showDrawer(res.data)
  } catch (e) {
    message.error(e.msg)
    errorSentry.captureError(e)
  }
}

// ------------------------------- 导出和导入 ---------------------------------
// 导出
function onExport() {
  const { page, limit, ...filter } = queryForm.value
  const data = {
    filter: JSON.stringify(filter),
    op: JSON.stringify(queryFormOp)
  }
  contractApi.exportXlsx(data)
}
// ------------------------------- 审核 ---------------------------------
function review(rowData) {
  Modal.confirm({
    title: '提示',
    content: '确定要审核【' + rowData.no + '】吗?',
    okText: '确定',
    okType: 'danger',
    onOk() {
      singleCancel(rowData)
    },
    cancelText: '取消',
    onCancel() {}
  })
}

async function singleCancel(rowData) {
  try {
    loadingStore.show()
    const res = await contractApi.modifyBook({ id: rowData.id, field: 'status', value: 2 })
    message.success(res.msg)
    queryData()
  } catch (e) {
    message.error(e.msg)
    errorSentry.captureError(e)
  } finally {
    loadingStore.hide()
  }
}
// ------------------------------- 终止 ---------------------------------
function terminate(rowData) {
  Modal.confirm({
    title: '提示',
    content: '确定要终止【' + rowData.no + '】吗?',
    okText: '确定',
    okType: 'danger',
    onOk() {
      singleCancelTerminate(rowData)
    },
    cancelText: '取消',
    onCancel() {}
  })
}

async function singleCancelTerminate(rowData) {
  try {
    loadingStore.show()
    const res = await contractApi.modifyBook({ id: rowData.id, field: 'status', value: 3 })
    message.success(res.msg)
    queryData()
  } catch (e) {
    message.error(e.msg)
    errorSentry.captureError(e)
  } finally {
    loadingStore.hide()
  }
}
</script>
